#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
商户文件上传相关接口调用示例
"""

import json
import os
import sys
import uuid
import logging
import base64
import hashlib

# 添加项目根目录到Python路径，确保能够导入jlpay包
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from jlpay.base.config import OrgConfig
from jlpay.services.file_service import FileService
from jlpay.model.upload import ImageUploadRequest, VideoUploadRequest, PdfUploadRequest, FileUploadResponse
from jlpay.utils.log_config import configure_rotating_file_logging

# =================== 常量定义 =====================
# 文件类型常量
FILE_TYPE_IMAGE = "image"
FILE_TYPE_VIDEO = "video"
FILE_TYPE_PDF = "pdf"

# 日志配置常量
LOG_FORMAT = '%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'
MAX_LOG_SIZE = 10 * 1024 * 1024  # 10MB
MAX_BACKUP_COUNT = 10

# =================== 日志配置 =====================
# 配置日志系统，使用滚动文件处理器
log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs")
root_logger = configure_rotating_file_logging(
    level=logging.INFO,
    log_dir=log_dir,
    log_name_prefix="jlpay",
    log_format=LOG_FORMAT,
    max_bytes=MAX_LOG_SIZE,
    backup_count=MAX_BACKUP_COUNT,
    propagate=True,
    module_levels={
        'jlpay.http': logging.DEBUG,
        'jlpay.service': logging.INFO,
        'examples': logging.INFO
    }
)

# 获取示例程序的logger实例
logger = logging.getLogger("examples.merchant_file_upload")
logger.setLevel(logging.INFO)

# =================== 密钥配置 =====================
# SM2公私钥
sm2_public_key_pem = """-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEJJhFmjeMRp9GwShxtWunv6Wny//m
Dg2pcnu0llDQvIYo5O3R+al39NekciZ0BIrT21Y/QJrXgJIoyBr6STml6g==
-----END PUBLIC KEY-----"""

sm2_private_key_pem = """-----BEGIN EC PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgHqOp471SMDsQml2G
2ErpZPLD2X7rbMqa6P1O9Zqlhe+gCgYIKoEcz1UBgi2hRANCAAQkmEWaN4xGn0bB
KHG1a6e/pafL/+YODalye7SWUNC8hijk7dH5qXf016RyJnQEitPbVj9AmteAkijI
GvpJOaXq
-----END EC PRIVATE KEY-----"""

# 嘉联支付平台公钥
jlpay_pub_key_pem = """-----BEGIN PUBLIC KEY-----
MIIBMzCB7AYHKoZIzj0CATCB4AIBATAsBgcqhkjOPQEBAiEA/////v//////////
//////////8AAAAA//////////8wRAQg/////v////////////////////8AAAAA
//////////wEICjp+p6dn140TVqeS89lCafzl4n1FauPkt28vUFNlA6TBEEEMsSu
LB8ZgRlfmQRGajnJlI/jC7/yZgvhcVpFiTNMdMe8Nzai9PZ3nFm9zuNraSFT0KmH
fMYqR0AC3zLlITnwoAIhAP////7///////////////9yA99rIcYFK1O79Ak51UEj
AgEBA0IABKZ3VWwH0Aw9xvOWXb+xM2gXyApWEAZLFy8UyIigp3ehOTwPJ693njrg
NavTLdzAtFBqXRreivlwBTIFy8iRgn8=
-----END PUBLIC KEY-----"""

# =================== 工具函数 =====================
def create_config():
    """创建配置对象"""
    config = OrgConfig.builder() \
        .app_id("1vzougr30f9vcw") \
        .url("https://upload-uat.jlpay.com") \
        .org_pri_key(sm2_private_key_pem) \
        .org_pub_key(sm2_public_key_pem) \
        .jlpay_pub_key(jlpay_pub_key_pem) \
        .build()
    return config

def send_request_and_handle_response(service, request, operation_name):
    """发送请求并处理响应"""
    try:
        # 根据请求类型调用不同的服务方法
        if isinstance(request, ImageUploadRequest):
            response = service.upload_image(request)
        elif isinstance(request, VideoUploadRequest):
            response = service.upload_video(request)
        elif isinstance(request, PdfUploadRequest):
            response = service.upload_pdf(request)
        else:
            logger.error(f"不支持的请求类型: {type(request)}")
            return None
        
        if response.is_success():
            logger.info(f"{operation_name}成功！")
            if hasattr(response, 'media_id'):
                logger.info(f"媒体文件ID: {response.media_id}")
            return response
        else:
            logger.error(f"{operation_name}失败: {response.ret_code} - {response.ret_msg}")
            return None
            
    except Exception as e:
        logger.error(f"请求异常: {str(e)}")
        return None

# =================== 示例函数 =====================
def image_upload_demo(image_path):
    """图片上传示例"""
    logger.info("开始执行图片上传示例")
    
    # 创建配置对象和文件服务
    config = create_config()
    file_service = FileService(config)
    
    # 创建图片上传请求
    request = ImageUploadRequest()
    request.set_file_from_path(image_path)
    
    # 发送请求
    response = send_request_and_handle_response(file_service, request, "图片上传")
    
    logger.info("图片上传示例执行完毕")
    return response.get_media_id() if response else None


def video_upload_demo(video_path):
    """视频上传示例"""
    logger.info("开始执行视频上传示例")
    
    # 创建配置对象和文件服务
    config = create_config()
    file_service = FileService(config)
    
    # 创建视频上传请求
    request = VideoUploadRequest()
    request.set_file_from_path(video_path)
    
    # 发送请求
    response = send_request_and_handle_response(file_service, request, "视频上传")
    
    logger.info("视频上传示例执行完毕")
    return response.get_media_id() if response else None


def pdf_upload_demo(pdf_path):
    """PDF上传示例"""
    logger.info("开始执行PDF上传示例")
    
    # 创建配置对象和文件服务
    config = create_config()
    file_service = FileService(config)
    
    # 创建PDF上传请求
    request = PdfUploadRequest()
    request.set_file_from_path(pdf_path)
    
    # 发送请求
    response = send_request_and_handle_response(file_service, request, "PDF上传")
    
    logger.info("PDF上传示例执行完毕")
    return response.get_media_id() if response else None


if __name__ == "__main__":
    # 示例文件路径，根据实际情况替换
    sample_image_path = "./sample_files/test_image.png"
    sample_video_path = "./sample_files/test_video.mp4"
    sample_pdf_path = "./sample_files/test_document.pdf"
    
    # 确保示例文件目录存在
    sample_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sample_files")
    if not os.path.exists(sample_dir):
        os.makedirs(sample_dir)
        logger.info(f"创建了示例文件目录: {sample_dir}")
        logger.info(f"请在此目录中放置测试用的图片、视频和PDF文件，并更新本脚本中的文件路径")
    
    logger.info("=" * 50)
    logger.info("===== 商户文件上传示例 开始 =====")
    logger.info("=" * 50)
    
    # 检查文件是否存在，执行对应的示例
    if os.path.exists(sample_image_path):
        logger.info("\n" + "=" * 50)
        logger.info("===== 图片上传示例 开始 =====")
        logger.info("=" * 50)
        image_upload_demo(sample_image_path)
    else:
        logger.warning(f"图片文件不存在: {sample_image_path}")
    
    if os.path.exists(sample_video_path):
        logger.info("\n" + "=" * 50)
        logger.info("===== 视频上传示例 开始 =====")
        logger.info("=" * 50)
        video_upload_demo(sample_video_path)
    else:
        logger.warning(f"视频文件不存在: {sample_video_path}")
    
    if os.path.exists(sample_pdf_path):
        logger.info("\n" + "=" * 50)
        logger.info("===== PDF上传示例 开始 =====")
        logger.info("=" * 50)
        pdf_upload_demo(sample_pdf_path)
    else:
        logger.warning(f"PDF文件不存在: {sample_pdf_path}")
    
    logger.info("\n" + "=" * 50)
    logger.info("===== 所有示例执行完毕 =====")
    logger.info("=" * 50) 